import Footer from '@/components/Footer';
import type { RunTimeLayoutConfig } from '@umijs/max';
import {history, useModel} from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { AvatarDropdown } from './components/RightContent/AvatarDropdown';
import { requestConfig } from './requestConfig';
import { getLoginUserUsingGet } from '@/services/backend/userController';
import { LinkOutlined } from '@ant-design/icons';
import { BACKEND_HOST_LOCAL, BACKEND_HOST_PROD } from '@/constants';
import {SettingDrawer} from "@ant-design/pro-layout";

const isDev = process.env.NODE_ENV === 'development';

/**
 * 无需用户登录态的页面
 */
const loginPath = '/user/login';
const registerPath = '/user/register';
const NO_NEED_LOGIN_WHITE_LIST = [registerPath, loginPath];

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialState> {
  const initialState: InitialState = {
    currentUser: undefined,
    settings: defaultSettings,
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (!NO_NEED_LOGIN_WHITE_LIST.includes(location.pathname)) {
    try {
      const res = await getLoginUserUsingGet();
      initialState.currentUser = res.data;
    } catch (error: any) {
      // 如果未登录
    }

    // 模拟登录用户
    // const mockUser: API.LoginUserVO = {
    //   userAvatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
    //   userName: 'admin',
    //   userRole: 'admin',
    // };
    // initialState.currentUser = mockUser;
  }
  return initialState;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
// @ts-ignore
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const { setInitialState } = useModel('@@initialState');
  const baseURL = isDev ? BACKEND_HOST_LOCAL : BACKEND_HOST_PROD;
  const apiURL = `${baseURL}/doc.html`;

  return {
    // avatarProps: {
    //   render: () => {
    //     return <AvatarDropdown />;
    //   },
    // },
    waterMarkProps: {
      content: initialState?.currentUser?.userName,
    },
    footerRender: () => <Footer />,
    links: isDev
      ? [
          <a key="openapi" href={apiURL} target="_blank" rel="noopener noreferrer">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </a>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          <AvatarDropdown  />
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = requestConfig;
